package com.example.zhifubao.web;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.zhifubao.AliPay;
import com.example.zhifubao.entity.PayCloseVo;
import com.example.zhifubao.entity.PayCreateVo;

import com.example.zhifubao.entity.PayRefundVo;
import com.example.zhifubao.entity.PayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Map;

@Controller
@RequestMapping("/pay")
public class WebController {


    @Autowired
    AliPay aliPay;


    @ResponseBody
    @PostMapping("create")
    public Object create(PayCreateVo payCreateVo) throws AlipayApiException {

        payCreateVo.setOut_trade_no(orderTime());


        return aliPay.orderCreate(payCreateVo);
    }


    @GetMapping("create")
    public Object createPage(){
        return  "pay";
    }


    @GetMapping("close")
    public Object orderClosePage() throws AlipayApiException {
        return  "close";
    }

    @ResponseBody
    @PostMapping("close")
    public Object orderClose(PayCloseVo payCloseVo) throws AlipayApiException {

        System.out.println(JSON.toJSONString(payCloseVo));
        return  aliPay.orderClose(payCloseVo);
    }



    @GetMapping("refund")
    public Object refundPage() throws AlipayApiException {
        return "refund";
    }


    @ResponseBody
    @PostMapping("refund")
    public Object orderRefund(PayRefundVo payRefundVo) throws AlipayApiException {

        System.out.println(JSON.toJSONString(payRefundVo));
        return  aliPay.orderRefund(payRefundVo);
    }









    @ResponseBody
    @GetMapping("authResult")
    public Object pay(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {


        return  aliPay.getCheck(request);
    }


    private   String orderTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(System.currentTimeMillis());
    }

}
